//
//  XQIdentityErrorController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/23.
//

#import "XQIdentityErrorController.h"
#import "XQCustomEngeLabel.h"
#import "XQIdentitySuccessView.h"
#import "XQIdentityErrorView.h"
#import "XQIdentityController.h"
#import "XQActionSheet.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>

@interface XQIdentityErrorController ()<UIImagePickerControllerDelegate>
@property (nonatomic,strong) XQCustomEngeLabel *topLabel;
@property (nonatomic,strong) XQIdentitySuccessView *successView;
@property (nonatomic,strong) XQIdentityErrorView *errorView;
@property (nonatomic,strong) XQButton *bottomButton;
@property (nonatomic,copy) NSArray *photoImages;
@property (nonatomic,copy) NSArray *faceImages;
@property (nonatomic,copy) NSArray *photoTexts;
@property (nonatomic,copy) NSArray *faceTexts;
@end

@implementation XQIdentityErrorController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    [self initData];
    [self makeUI];
    [self makeConstraints];
    
    self.startInterval = [XQTimeTool nowTimeStamp];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopLocation];
}

- (void)initData {
    self.photoImages = @[@"photo_error1",@"photo_error2",@"photo_error3"];
    self.faceImages = @[@"face_error1",@"face_error2",@"face_error3"];
    self.photoTexts = @[@"Blurring",@"Missing border",@"Strong flash"];
    self.faceTexts = @[@"Face is not \naligned",@"Strong flash",@"Unstable light"];
}

- (void)makeUI {
   
    self.view.backgroundColor = kCardColor;
    [self.view addSubview:self.topLabel];
    [self.view addSubview:self.successView];
    [self.view addSubview:self.errorView];
    [self.view addSubview:self.bottomButton];
}

- (void)makeConstraints {
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight + 20);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(70);
    }];
    [self.successView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topLabel.mas_bottom).offset(20);
        make.left.right.equalTo(@0);
    }];
    [self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.successView.mas_bottom).offset(20);
        make.left.right.equalTo(@0);
    }];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-[UIScreen mainScreen].bottomHeight - 20);
        make.left.right.equalTo(@0);
    }];
}

#pragma mark - setter

- (void)setTopTitle:(NSString *)topTitle {
    [self.navigationBar setTitle:topTitle];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    BOOL isCamera = picker.sourceType == UIImagePickerControllerSourceTypeCamera;
    [self dismissViewControllerAnimated:YES completion:^{
        [self uploadPhoto:image isCamera:isCamera];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - private

- (void)sureClick {
    
    if (!self.isPhoto) {
        [self openCamera];
        return;
    }
    
    @weakify(self);
    XQActionSheet *sheet = [XQActionSheet sheetWithButtonTitles:@[@"Select from the album",@"Take Photo"] andCancleTitle:@"Cancel" clicked:^(NSInteger buttonIndex) {
        @strongify(self);
        if (buttonIndex == 0) {
            [self openPhotoLibrary];
        } else if (buttonIndex == 1) {
            [self openCamera];
        }
    }];
    [sheet show];
}

- (void)uploadPhoto:(UIImage *)image isCamera:(BOOL)isCamera {
    NSString *colliding = isCamera ? @"1" : @"2";
    NSString *spacemobile = self.isPhoto ? @"11" : @"10";
    NSString *maneuvers = self.maneuvers.length ? self.maneuvers : @"";
    NSData *imgData = [image dataOfCompressedToMaxByte:512*1024];
    
    NSMutableDictionary *dic = @{
        @"colliding" : colliding,
        @"spacemobile" : spacemobile,
    }.mutableCopy;
    if (self.isPhoto) {
        [dic setValue:maneuvers forKey:@"maneuvers"];
    }
    
    [XQHUD showLoadingInView:self.view];
    @weakify(self);
    [XQAFNetworking uploadImageUrl:[XQNetManager getAbsolutePath:@"/direct/distress"]  pars:dic imageData:imgData callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            [self back:responseObject[@"accomplish"]  maneuvers:self.isPhoto ? maneuvers : @""];
        }else {
            [XQToast showMsg:responseObject[@"loon"]];
        }
    }];
}

- (void)back:(NSDictionary *)dic maneuvers:(NSString *)maneuvers {
    NSArray *viewControllers = self.navigationController.viewControllers;
    for (UIViewController *vc in viewControllers) {
        if ([vc isKindOfClass:[XQIdentityController class]]) {
            XQIdentityController *identityController = (XQIdentityController *)vc;
            [identityController saveUserInfo:dic maneuvers:maneuvers startTime:self.startInterval longitude:self.longitude latitude:self.latitude];
            [self.navigationController popToViewController:identityController animated:YES];
            break;;
        }
    }
}

- (void)openPhotoLibrary {
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            // 用户授权了相册权限
            dispatch_async(dispatch_get_main_queue(), ^{
                // 从本地相册中获取
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                picker.delegate = (id)self;
                //设置选择后的图片可被编辑
                picker.allowsEditing = YES;
                [self presentViewController:picker animated:YES completion:nil];
            });
        } else {
            if (authStatus == PHAuthorizationStatusDenied) {
                // 用户拒绝了相册权限
                dispatch_async(dispatch_get_main_queue(), ^{
                    [XQAlertController showAccessDeniedAlert:self message:@"Please enable access to PhotoLibrary in Settings."];
                });
            }
        }
    }];
}

- (void)openCamera {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
       if (granted) {
           // 用户授权了相机权限
           dispatch_async(dispatch_get_main_queue(), ^{
               if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                   UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                   picker.delegate = (id)self;
                   picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                   picker.cameraDevice = self.isPhoto ? UIImagePickerControllerCameraDeviceRear : UIImagePickerControllerCameraDeviceFront;
                   [self presentViewController:picker animated:YES completion:nil];
               }
           });
       } else {
           if (authStatus == AVAuthorizationStatusDenied) {
               // 用户拒绝了相机权限
               dispatch_async(dispatch_get_main_queue(), ^{
                   [XQAlertController showAccessDeniedAlert:self message:@"Please enable access to Camera in Settings."];
               });
           }
       }
   }];
}

#pragma mark - lazy

- (XQCustomEngeLabel *)topLabel {
    if (!_topLabel) {
        _topLabel = [XQCustomEngeLabel new];
        _topLabel.text = @"When performing recognition, follow \ntheinstructions to complete the action";
        _topLabel.edgtInsets = UIEdgeInsetsMake(12, 6, 12, 6);
        _topLabel.numberOfLines = 0;
        _topLabel.textColor = [UIColor whiteColor];
        _topLabel.font = [UIFont systemFontOfSize:16];
        _topLabel.backgroundColor = kOrangeColor;
        _topLabel.layer.cornerRadius = 15;
        _topLabel.layer.masksToBounds = YES;
        _topLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _topLabel;
}

- (XQIdentitySuccessView *)successView {
    if (!_successView) {
        _successView = [[XQIdentitySuccessView alloc] init];
        _successView.imageName = self.isPhoto ? @"photo_success" : @"face_bg";
    }
    return _successView;
}

- (XQIdentityErrorView *)errorView {
    if (!_errorView) {
        _errorView = [[XQIdentityErrorView alloc] init];
        [_errorView setImages:self.isPhoto ? self.photoImages : self.faceImages];
        [_errorView setTexts:self.isPhoto ? self.photoTexts : self.faceTexts];
    }
    return _errorView;
}

- (XQButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [[XQButton alloc] initWithTitle:@"OK"];
        @weakify(self);
        _bottomButton.onTapHandle = ^{
            @strongify(self);
            [self sureClick];
        };
    }
    return _bottomButton;
}

@end
